package com.jms.service.sys.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jms.dao.BaseDaoI;
import com.jms.model.sys.Tplan;
import com.jms.model.sys.Tresource;
import com.jms.model.sys.Trole;
import com.jms.pageModel.base.PageFilter;
import com.jms.pageModel.base.Tree;
import com.jms.pageModel.sys.Plan;
import com.jms.pageModel.sys.Resource;
import com.jms.pageModel.sys.Role;
import com.jms.service.sys.PlanServiceI;
import com.jms.utils.StringUtil;

@Service
public class PlanServiceImpl implements PlanServiceI {

	@Autowired
	private BaseDaoI<Tplan> planDao;

	@Override
	public List<Plan> dataGrid(Plan plan, PageFilter ph) {
		List<Plan> ul = new ArrayList<Plan>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tplan t ";
		List<Tplan> l = planDao.find(hql + whereHql(plan, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		for (Tplan t : l) {
			Plan u = new Plan();
			BeanUtils.copyProperties(t, u);
			if(t.getMode()==1){u.setModename("定时运行");}
			if(t.getMode()==2){u.setModename("循环运行");}
			if(t.getMode()==3){u.setModename("定时循环运行");}
			ul.add(u);
		}
		return ul;
	}

	@Override
	public Long count(Plan plan, PageFilter ph) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tplan t ";
		return planDao.count("select count(*) " + hql + whereHql(plan, params), params);
	}

	@Override
	public void add(Plan p) {
		Tplan t = new Tplan();
		StringUtil.beanCopy(p, t, false);
		planDao.save(t);
	}

	@Override
	public void delete(Long id) {
		Tplan t = planDao.get(Tplan.class, id);
		planDao.delete(t);
		
	}

	@Override
	public void edit(Plan p) {
		Tplan t = planDao.get(Tplan.class, p.getId());
		StringUtil.beanCopy(p, t, false);
		planDao.update(t);
		
	}

	@Override
	public Plan get(Long id) {
		Tplan t = planDao.get(Tplan.class, id);
		Plan p = new Plan();
		BeanUtils.copyProperties(t, p);
		
		return p;
	}

	@Override
	public void grant(Plan plan) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Tree> tree() {
		// TODO Auto-generated method stub
		return null;
	}


	private String whereHql(Plan plan, Map<String, Object> params) {
		String hql = "";
		if (plan != null) {
			hql += " where 1=1 ";
			if (plan.getName() != null) {
				hql += " and t.name like :name";
				params.put("name", "%%" + plan.getName() + "%%");
			}
		}
		return hql;
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	
}
